package com.liya.service.impl;

import com.liya.Dao.UserDao;
import com.liya.Dao.UserRoleDao;
import com.liya.pojo.Role;
import com.liya.pojo.User;
import com.liya.pojo.UserRole;
import com.liya.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author LiYa
 * @version 1.0
 * @className UserServiceImpl
 * @description TODO
 * @science 2020/9/22 19:48
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao;
    private UserRoleDao userRoleDao;
    @Autowired
    public UserServiceImpl(UserDao userDao, UserRoleDao userRoleDao) {
        this.userDao = userDao;
        this.userRoleDao = userRoleDao;
    }

    @Override
    public Set<User> getAll() {
        return userDao.queryAll();
    }

    @Override
    public boolean addOne(User user) {
        int result = userDao.insertByUser(user);
        //判断添加的用户的角色信息是否为空
        if(user.getRoles() != null){
            //遍历用户的角色，以循环执行user_role表的插入动作
            for(Role role:user.getRoles()){
                //构造UserRole对象
                UserRole userRole = new UserRole();
                userRole.setRoleId(role.getRoleId());
                userRole.setUserId(user.getUserId());
                //让userRoleDao执行插入UserRole
                userRoleDao.insert(userRole);
            }
        }
        return result > 0;
    }

    @Override
    public boolean removeOne(User user) {
        int result = userDao.deleteByUser(user);
        return result > 0;
    }

    @Override
    public boolean modifyOne(User user) {
        int result = userDao.updateByUser(user);
        return result > 0;
    }

    @Override
    public boolean removeSome(Set<Integer> userIds) {
        int result = userDao.deleteByIds(userIds);
        return result > 0;
    }

    @Override
    public Set<User> getUserThatAddressLike(String address) {
        String column = "address";
        return userDao.queryByColumn(column, address);
    }

    @Override
    public Set<User> getUserWithMultiCondition(String userName, String userPhone, String roleName) {
        return userDao.queryByMultiConditions(userName, userPhone, roleName);
    }
}
